import React, { useRef, useState } from 'react';
import { Button, Descriptions, Drawer, Flex, Form, Input, Space, Statistic } from 'antd';
import { ProTable, ProColumns } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { fetchFinancialStats, fetchOrderList, exportData, viewFinance } from '@/services/ant-design-pro/financial';
import type { ActionType } from '@ant-design/pro-components';
import { css } from 'antd-style';

const FinancialStats: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<any | undefined>(undefined);
  const [statsData, setStatsData] = useState<{ orderCount: number; payOrderCount: number; totalAmount: number }>({
    orderCount: 0,
    payOrderCount: 0,
    totalAmount: 0,
  });
  const [statsLoading, setStatsLoading] = useState<boolean>(false);

  const handleExport = async () => {
    const data = await exportData();
    console.log(data);
  };

  const showDetail = async (record: any) => {
    const detail = await viewFinance(record.id);
    setCurrentRecord(detail);
    setDrawerVisible(true);
  };

  const columns: ProColumns<any>[] = [
    {
      title: '订单编号',
      dataIndex: 'orderCode',
      width: 150,
      ellipsis: true,
    },
    {
      title: '名称',
      dataIndex: 'orderName',
      width: 100,
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      width: 120,
      ellipsis: true,
    },
    {
      title: '订单金额',
      dataIndex: 'orderAmount',
      width: 100,
      ellipsis: true,
    },
    {
      title: '下单时间',
      dataIndex: 'orderTime',
      valueType: 'date',
      width: 150,
      ellipsis: true,
      render: (_, record) => (
        <>
          {
            record.orderTime
          }
        </>
      )
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      valueType: 'date',
      width: 150,
      ellipsis: true,
      render: (_, record) => (
        <>
          {
            record.payTime
          }
        </>
      )
    },
    {
      title: '支付方式',
      dataIndex: 'payType',
      width: 100,
      ellipsis: true,
      valueEnum: {
        0: '支付宝',
        1: '微信',
        2: '对公支付',
        3: '免费'
      },
    },
    {
      title: '发票状态',
      dataIndex: 'billStatus',
      width: 100,
      ellipsis: true,
      valueEnum: {
        0: '未开',
        1: '开票中',
        2: '已开',
      },
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      width: 100,
      ellipsis: true,
      valueEnum: {
        0: '待支付',
        1: '已完成',
        2: '已取消',
        3: '待退款',
        4: '已退款',
        5: '审核拒绝',
        6: '订单超时',
        7: '退款失败',
      },
    },
    {
      title: '操作',
      fixed: 'right',
      width: 80,
      valueType: 'option',
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            showDetail(record);
          }}
        >
          查看
        </a>,
      ],
    },
  ];



  return (
    <>
      <ProTable<any>
        scroll={{ x: 1300 }}
        actionRef={actionRef}
        rowKey="orderNumber"

        search={{
          labelWidth: 'auto',
        }}
        request={async (params) => {
          setStatsLoading(true);
          const result = await fetchOrderList(params);
          setStatsData({
            orderCount: result.orderCount,
            payOrderCount: result.payOrderCount,
            totalAmount: result.totalAmount,
          });
          setStatsLoading(false);
          return result;
        }}
        headerTitle={
          <div style={{ width: '100px', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            订单列表
          </div>
        }
        options={false}
        columns={columns}
        toolBarRender={() => [
          <Space key="stats" align="center" style={{ marginRight: 16,display:'flex' , whiteSpace: 'nowrap'}}>
            <Space align="center">
              <span>订单数量:</span>
              <Statistic valueStyle={{ fontSize: '16px' }}  value={statsData.orderCount} loading={statsLoading} />
            </Space>
            <Space align="center">
              <span>已支付订单数量:</span>
              <Statistic valueStyle={{ fontSize: '16px' }} value={statsData.payOrderCount} loading={statsLoading} />
            </Space>
            <Space align="center">
              <span>总收入:</span>
              <Statistic valueStyle={{ fontSize: '16px' }} value={statsData.totalAmount} precision={2} loading={statsLoading} prefix="¥" />
            </Space>
          </Space>,
          <Button type='primary' key={'export'} onClick={handleExport}>导出</Button>
        ]}
      />

      <Drawer
        title="财务明细"
        width={1000}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        footer={
          <Space>
            <Button onClick={() => setDrawerVisible(false)}>关闭</Button>
          </Space>
        }
      >
        {currentRecord && (
          <>
            <Descriptions title="订单详情" bordered style={{ marginTop: 24 }} column={2}>
              <Descriptions.Item label="订单编号">{currentRecord.orderCode || '-'}</Descriptions.Item>
              <Descriptions.Item label="订单名称">{currentRecord.orderName || '-'}</Descriptions.Item>
              <Descriptions.Item label="手机号">{currentRecord.mobile || '-'}</Descriptions.Item>
              <Descriptions.Item label="邮箱">{currentRecord.email || '-'}</Descriptions.Item>
              <Descriptions.Item label="用户名称">{currentRecord.userName || '-'}</Descriptions.Item>
              <Descriptions.Item label="企业名称">{currentRecord.companyName || '-'}</Descriptions.Item>
              <Descriptions.Item label="地址">{currentRecord.companyAddress || '-'}</Descriptions.Item>
              <Descriptions.Item label="订单金额">{currentRecord.orderAmount || '-'}</Descriptions.Item>
              <Descriptions.Item label="最新金额">{currentRecord.newOrderAmount || '-'}</Descriptions.Item>
              <Descriptions.Item label="原始订单金额">{currentRecord.originalAmount || '-'}</Descriptions.Item>
              <Descriptions.Item label="实付金额">{currentRecord.payAmount || '-'}</Descriptions.Item>
              <Descriptions.Item label="下单时间">{currentRecord.orderTime || '-'}</Descriptions.Item>
              <Descriptions.Item label="支付时间">{currentRecord.payTime || '-'}</Descriptions.Item>
              <Descriptions.Item label="支付方式">{currentRecord.payType === '0' ? '支付宝' : currentRecord.payType === '1' ? '微信' : currentRecord.payType === '2' ? '对公支付' : '-'}</Descriptions.Item>
              <Descriptions.Item label="发票状态">{currentRecord.billStatus === 0 ? '未开' : currentRecord.billStatus === 1 ? '开票中' : currentRecord.billStatus === 2 ? '已开票' : '-'}</Descriptions.Item>
              <Descriptions.Item label="订单状态">{currentRecord.orderStatus === 0 ? '待支付' : currentRecord.orderStatus === 1 ? '已完成' : currentRecord.orderStatus === 2 ? '已取消' : currentRecord.orderStatus === 3 ? '待退款' : currentRecord.orderStatus === 4 ? '已退款' : currentRecord.orderStatus === 5 ? '审核拒绝' : currentRecord.orderStatus === 6 ? '订单超时失效' : '-'}</Descriptions.Item>
              <Descriptions.Item label="审核状态">{currentRecord.auditStatus === 0 ? '待审核' : currentRecord.auditStatus === 1 ? '已审核' : currentRecord.auditStatus === 2 ? '已驳回' : '-'}</Descriptions.Item>
              <Descriptions.Item label="订单类型">{currentRecord.orderType === '0' ? '数据产品' : currentRecord.orderType === '1' ? '其它产品' : '-'}</Descriptions.Item>
              <Descriptions.Item label="产品名称">{currentRecord.productName || '-'}</Descriptions.Item>
              <Descriptions.Item label="产品类型">{currentRecord.productType === '1' ? '免费版' : currentRecord.productType === '2' ? '包年版' : currentRecord.productType === '3' ? '个性定制版' : '-'}</Descriptions.Item>
              <Descriptions.Item label="注册时间">{currentRecord.registerTime || '-'}</Descriptions.Item>
              <Descriptions.Item label="创建时间">{currentRecord.createTime || '-'}</Descriptions.Item>
              <Descriptions.Item label="更新时间">{currentRecord.updateTime || '-'}</Descriptions.Item>
              <Descriptions.Item label="备注">{currentRecord.remark || '-'}</Descriptions.Item>
            { currentRecord.applicationReason && <Descriptions.Item label="退款申请理由">{currentRecord.applicationReason || '-'}</Descriptions.Item>}
             { currentRecord.applicationRemark&& <Descriptions.Item label="退款申请理由备注">{currentRecord.applicationRemark || '-'}</Descriptions.Item>}
            </Descriptions>

            {currentRecord.orderDetailList && currentRecord.orderDetailList.length > 0 && (
              <Descriptions title="订单明细" bordered style={{ marginTop: 24 }} layout="vertical" column={2}>
                {currentRecord.orderDetailList.map((detail, index) => (
                  <React.Fragment key={index}>
                    <Descriptions.Item label="费用">{detail.amount || '-'}</Descriptions.Item>
                    <Descriptions.Item label="调用量">{detail.callCount || '-'}</Descriptions.Item>
                    <Descriptions.Item label="调用方式">{detail.callWay || '-'}</Descriptions.Item>
                    <Descriptions.Item label="创建人id">{detail.createId || '-'}</Descriptions.Item>
                    <Descriptions.Item label="创建时间">{detail.createTime || '-'}</Descriptions.Item>
                    <Descriptions.Item label="数据类型">{detail.dataType || '-'}</Descriptions.Item>
                    <Descriptions.Item label="生效时间">{detail.effectTime || '-'}</Descriptions.Item>
                    <Descriptions.Item label="到期时间">{detail.expirationTime || '-'}</Descriptions.Item>
                    <Descriptions.Item label="全球城市">{detail.globalCity || detail.weatherType || '-'}</Descriptions.Item>
                    <Descriptions.Item label="订单编码">{detail.orderCode || '-'}</Descriptions.Item>
                    <Descriptions.Item label="订单名称">{detail.orderName || '-'}</Descriptions.Item>
                    <Descriptions.Item label="服务城市">{detail.serviceCity || '-'}</Descriptions.Item>
                    <Descriptions.Item label="服务时长">{detail.serviceTime || '-'}</Descriptions.Item>
                    <Descriptions.Item label="服务类别">{detail.serviceType || '-'}</Descriptions.Item>
                    <Descriptions.Item label="操作人id">{detail.updateId || '-'}</Descriptions.Item>
                    <Descriptions.Item label="更新时间">{detail.updateTime || '-'}</Descriptions.Item>
                    <Descriptions.Item label="使用状态">{detail.useStatus === 0 ? '待使用' : detail.useStatus === 1 ? '使用中' : detail.useStatus === 2 ? '已关闭' : detail.useStatus === 3 ? '待生效' : '-'}</Descriptions.Item>
                    <Descriptions.Item label="天气类型">{detail.weatherType || '-'}</Descriptions.Item>
                    <Descriptions.Item label="天气类型编码">{detail.weatherTypeCode || '-'}</Descriptions.Item>
                  </React.Fragment>
                ))}
              </Descriptions>
            )}
          </>
        )}
      </Drawer>
    </>
  );
};

export default FinancialStats;
